package com.wqj.ride.happyriding.bluetooth.bt

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.IntentFilter
import android.os.Bundle

import android.support.design.widget.FloatingActionButton
import android.support.v7.app.AppCompatActivity
import android.util.Log

import android.view.View
import android.widget.*
import android.widget.AdapterView.OnItemClickListener
import com.wqj.ride.happyriding.R
import com.wqj.ride.happyriding.bluetooth.bt.adapter.BtDevicesAdapter
import com.wqj.ride.happyriding.bluetooth.bt.bean.BluetoothDeviceDean
import com.wqj.ride.happyriding.bluetooth.bt.callback.BtConnectResult
import com.wqj.ride.happyriding.bluetooth.bt.manager.BtManager
import com.wqj.ride.happyriding.bluetooth.bt.receiver.BtBroadcastReceiver
import com.wqj.ride.happyriding.bluetooth.bt.ui.BtDevicesUi

import org.jetbrains.anko.find
import org.jetbrains.anko.setContentView

class BtDevicesActivity : AppCompatActivity() {
    var mlistView: ListView? = null
    var mScanBtn: FloatingActionButton? = null
    var mBtManager: BtManager? = null
    var mTitle: TextView? = null
    var mBackBtn: ImageView? = null

    var mScanedBtDevices: ArrayList<BluetoothDeviceDean> = ArrayList() // 扫描到的bt device
    var mBtEventReceiver: BtBroadcastReceiver?=null

    lateinit var mBtDevicesAdapter: BtDevicesAdapter
    val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    var mScanStatus: Int = STATUS_NORMAL

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBtDevicesAdapter = BtDevicesAdapter(mScanedBtDevices, this)
        BtDevicesUi().setContentView(this@BtDevicesActivity)

        mBackBtn    = find<ImageView>(BtDevicesUi.ID_BACK_BTN)
        mTitle      = find<TextView>(BtDevicesUi.ID_TITLE)
        mScanBtn    =  find<FloatingActionButton>(BtDevicesUi.ID_SCAN_BTN)
        mlistView   = find<ListView>(BtDevicesUi.ID_BT_DEVICES_LIST)

        mlistView!!.adapter = mBtDevicesAdapter
        mBtManager = BtManager.getInstance()

        val btConnectCallback: BtConnectResult = object: BtConnectResult {
            override fun onFailure() {
                runOnUiThread {
                    Toast.makeText(applicationContext, "连接失败", Toast.LENGTH_SHORT)
                            .show()
                    mBtDevicesAdapter.notifyDataSetChanged()
                    setStatus(STATUS_CONNECT_FAILURE)
                }
            }

            override fun onSuccess() {
                runOnUiThread {
                    Toast.makeText(applicationContext, "连接成功", Toast.LENGTH_SHORT)
                            .show()
                    mBtDevicesAdapter.notifyDataSetChanged()
                    setStatus(STATUS_CONNECTED)
                }
            }

        }

        mlistView?.setOnItemClickListener(object : OnItemClickListener {

            override fun onItemClick(arg0: AdapterView<*>, arg1: View?, arg2: Int,
                                     arg3: Long) {
                Log.i(TAG, "id: " + arg2)
                if (mScanedBtDevices[arg2].isContected) {
                    mBtManager!!.disconnect()
                    mScanedBtDevices[arg2].isContected = false
                    Toast.makeText(applicationContext, "断开连接成功", Toast.LENGTH_SHORT)
                            .show()
                    mBtDevicesAdapter.notifyDataSetChanged()
                    setStatus(STATUS_NORMAL)
                } else {
                    setStatus(STATUS_CONNECTING)
                    mBtManager!!.connect(mScanedBtDevices[arg2], btConnectCallback)

                }
            }
        })
        mScanBtn!!.setOnClickListener(object: View.OnClickListener{
            override fun onClick(v: View?) {
                Log.d(TAG, "scan button clicked");

                if (STATUS_NORMAL == mScanStatus) {
                    setStatus(STATUS_SCANING)
                } else if (STATUS_SCANING == mScanStatus) {
                    setStatus(STATUS_NORMAL)
                }
            }
        })
        mBackBtn!!.setOnClickListener(object: View.OnClickListener{
            override fun onClick(v: View?) {
                finish()
            }

        })

        mBtEventReceiver = BtBroadcastReceiver(this)

        val filter = IntentFilter()
        filter.addAction(BluetoothDevice.ACTION_FOUND)
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        registerReceiver(mBtEventReceiver, filter)
    }

    private fun setStatus(status: Int) {
        mScanStatus = status

        if (STATUS_NORMAL == status) {
            mBluetoothAdapter.cancelDiscovery()
            mScanBtn!!.setImageResource(R.mipmap.search_input)
            mTitle!!.text = "扫描完成"
        } else if (STATUS_SCANING == status) {
            mScanedBtDevices.clear()
            if (mBtManager!!.isConnected()) {
                mScanedBtDevices.add(mBtManager!!.getConnectedDevice())
            }
            mBtDevicesAdapter.notifyDataSetChanged()

            mBluetoothAdapter.cancelDiscovery()
            mBluetoothAdapter.startDiscovery()

            mTitle!!.text = "扫描中..."
            mScanBtn!!.setImageResource(R.mipmap.up)
        } else if (STATUS_CONNECTED == status) {
            mTitle!!.text = "已连接"
        } else if (STATUS_CONNECTING == status) {
            mTitle!!.text = "正在连接..."
            mBluetoothAdapter.cancelDiscovery()
            mScanBtn!!.setImageResource(R.mipmap.search_input)
        } else if (STATUS_CONNECT_FAILURE == status) {
            mTitle!!.text = "连接失败"
        }
    }

    override fun onStart() {
        super.onStart()
        // 打开蓝牙
        if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
            BluetoothAdapter.getDefaultAdapter().enable();
        }
        // 已连接bt device, 则不扫描
        if (mBtManager!!.isConnected()) {
            mScanedBtDevices.add(mBtManager!!.getConnectedDevice())
            mBtDevicesAdapter.notifyDataSetChanged()
        } else {
            setStatus(STATUS_SCANING)
        }
    }

    override fun onStop() {
        super.onStop()
        unregisterReceiver(mBtEventReceiver)
        setStatus(STATUS_NORMAL)
    }

     companion object{
        val TAG: String = "BluetoothDevices"
        val BT_DEVICE_NAME = "HYBike"
        val BT_UUID = "00001101-0000-1000-8000-00805F9B34FB"

        val BT_SERVER_CONNECT_SUCCESS = 3
        val BT_SERVER_CONNECT_FAIL = 4

        val STATUS_NORMAL = 0
        val STATUS_SCANING = 1
        val STATUS_CONNECTED = 2
        val STATUS_CONNECTING = 3
        val STATUS_CONNECT_FAILURE = 4
    }
}
